package cn.edu.hitsz.compiler.parser;

import cn.edu.hitsz.compiler.NotImplementedException;
import cn.edu.hitsz.compiler.lexer.Token;
import cn.edu.hitsz.compiler.parser.table.Attribute;
import cn.edu.hitsz.compiler.parser.table.Production;
import cn.edu.hitsz.compiler.parser.table.Status;
import cn.edu.hitsz.compiler.parser.table.Term;
import cn.edu.hitsz.compiler.symtab.SourceCodeType;
import cn.edu.hitsz.compiler.symtab.SymbolTable;

import java.util.ArrayList;
import java.util.List;

// TODO: 实验三: 实现语义分析
public class SemanticAnalyzer implements ActionObserver {
    private SymbolTable table;

    /** 属性栈 */
    private List<Attribute> attr = new ArrayList<Attribute>();

    @Override
    public void whenAccept(Status currentStatus) {

    }

    @Override
    public void whenReduce(Status currentStatus, Production production) {
        switch (production.index()) {
            case 4 -> {     // S -> D id;
                /** pop id; get D.text; addTable(id.text, D.text) */
                Attribute ID = attr.remove(attr.size() - 1);
                String id = ID.getName();
                Attribute D = attr.remove(attr.size() - 1);
                String type = D.getName();


                if (table.has(id)) {
                    table.get(id).setType(SourceCodeType.Int);
                }
            }
        }
    }

    @Override
    public void whenShift(Status currentStatus, Token currentToken) {
        attr.add(new Attribute(currentToken.getText()));
    }

    @Override
    public void setSymbolTable(SymbolTable table) {
        this.table = table;
    }

    public SymbolTable getTable(){ return table; }
}

